import xbmc
import xbmcgui
import urllib, urllib2
import os, sys, re

__cwd__      = sys.modules[ "__main__" ].__cwd__
__settings__ = sys.modules[ "__main__" ].__settings__
__htm__      = sys.modules[ "__main__" ].__htm__
__fav__      = sys.modules[ "__main__" ].__fav__
__test__     = sys.modules[ "__main__" ].__test__
__vdata__    = sys.modules[ "__main__" ].__vdata__
__pos__      = sys.modules[ "__main__" ].__pos__

class GUI(xbmcgui.WindowXML):

	def __init__(self, *args, **kwargs):
		xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
		self.serie_id = kwargs['id']
		print 'Serie ID : [%s]' % self.serie_id
		self.doModal()

	def onInit(self):
		self.testmode = __settings__.getSetting('testmode')
		self.action_cancel_dialog = (9, 10)
		self.ep_list = self.getControl(92)
		self.ses_list = self.getControl(93)
		self.gen_list = self.getControl(99)
		self.star_list = self.getControl(88)
		self.fav_button = self.getControl(96)
		self.description = ''
		self.rating = ''
		self.selected_item = 0
		self.ses_list.reset()
		self.gen_list.reset()
		self.star_list.reset()
		# ===================================================
		# Add list items here :
		if __test__:
			__htm__.getPage( url=__cwd__ + '\\samples\\serie.htm', txdata=None )
			self.season_nr = '1'
		else:
			self.season_nr = __settings__.getSetting('ses-' + self.serie_id)
			if (len(self.season_nr)==0):
				self.season_nr = '1'
			__htm__.getPage( url='http://www.vplay.ro/serials/browse.do?sid=' + self.serie_id + '&ses=' + self.season_nr, txdata=None )
		stream = __htm__.Page

		self.getControl(57).setImage(__htm__.UserAvatar)
		self.getControl(58).setLabel(__htm__.UserID)
		self.getControl(59).setLabel(__htm__.UserDays + ' zile VIP')
			
		series_title = re.compile('<h1>(.+?)<').findall(stream)
		if (len(series_title)>0):
			self.getControl(95).setLabel(series_title[0])
		
		if __fav__.getFav( self.serie_id ):
			self.fav_button.setLabel('FAV')
		else:
			self.fav_button.setLabel('')
		
		self.series_img = 'http://i.vplay.ro/ch/' + self.serie_id + '.jpg'
		self.getControl(94).setImage(self.series_img)
		
		rating = re.compile('Not.+?<i>(.+?)</i>').findall(stream)
		if len(rating)>0:
			self.rating = rating[0]
			self.getControl(91).setLabel(self.rating)
		
		x1 = stream.find('div class="stars"')
		x2 = stream.find('</div>', x1)
		stars = re.compile('img src="(.+?)"').findall(stream[x1:x2])
		for star in stars:
			s = xbmcgui.ListItem(thumbnailImage=star)
			self.star_list.addItem(s)
			print 'Star : [%s]' % star
		
		x1 = stream.find('class="desc-lang">')
		if x1>=0:
			x2 = stream.find('</div>', x1)
			self.description = stream[x1 + 18 : x2].replace('\n',' ')
		else:
			self.getControl(97).setVisible(False)
			print 'No description available.'
		
		next_title = re.compile('"calendar-next-title">(.+?)</div>').findall(stream)
		next_date = re.compile('"calendar-monthyear">(.+?)</div>').findall(stream)
		next_day = re.compile('"calendar-day">(.+?)</div>').findall(stream)
		if (len(next_title) > 0):
			if(len(next_date) > 0):
				if(len(next_day) > 0):
					self.getControl(98).setLabel(next_title[0].replace('<span>','').replace('</span>',''))
					self.getControl(90).setLabel(next_day[0] + ' ' + next_date[0])
		else:
			self.getControl(89).setVisible(False)
		
		series_genres = re.compile('genreid=(.+?)">(.+?)<').findall(stream)
		if (len(series_genres)>0):
			for genre_id, genre_name in series_genres:
				item = xbmcgui.ListItem(label=genre_name)
				item.setProperty('id', genre_id)
				self.gen_list.addItem(item)
		
		if __test__:
			seasons = re.compile('sid=6&ses=(.+?)".*?>(.+?)<').findall(stream)
		else:
			seasons = re.compile('sid=' + self.serie_id + '&ses=(.+?)".*?>(.+?)<').findall(stream)
		if (len(seasons)>0):
			for season_id, season_name in seasons:
				item = xbmcgui.ListItem(label=season_name)
				item.setProperty('id', season_id)
				if season_id==self.season_nr:
					item.setInfo('video', {'trailer':'s'})
				else:
					item.setInfo('video', {'trailer':'n'})
				self.ses_list.addItem(item)
				if season_id==self.season_nr:
					self.ses_list.selectItem(int(season_id) - 1)
		
		self.loadEpisodes(stream)
		# ==================================================================

	def onClick(self, controlId):
		print 'Control ID : [%s]' % str(controlId)
		if controlId == 9001:
			print 'Main'
			
		elif controlId == 9003:
			import resources.lib.GenreList as GenreList
			page_genre_list = GenreList.GUI("vplay_genre_list.xml", __cwd__, "default")
			
		elif controlId == 9004:
			keyboard = xbmc.Keyboard('', 'Enter keyword:', False)
			kw = ''
			canceled = 'false'
			while (kw=='' and canceled=='false') :
				keyboard.doModal()
				if (keyboard.isConfirmed()):
					kw = keyboard.getText()
				if len(kw)==0:
					canceled='true'
			if canceled=='false':
				print 'Keyword : [%s]' % kw
				import resources.lib.Search as Search
				page_search = Search.GUI("vplay_search.xml", __cwd__, "default", keyword=kw)
				
		elif controlId == 9005:
			print 'Login'
			__settings__.openSettings()

		elif controlId == 92:
			item = self.ep_list.getSelectedItem()
			# ===========================================
			# PLAY the item!
			print 'Item : [%s]' % item.getLabel()
			print 'ID   : [%s]' % item.getProperty('id')
			__htm__.getVideo( item.getProperty('id') )
			p = sys.modules[ "__main__" ].vplayer( xbmc.PLAYER_CORE_AUTO, vid=__htm__.VideoUrl, subs=__htm__.Subtitles, id=item.getProperty('id'), listitem=item)
			# ===========================================
		
		elif controlId == 93:
			item = self.ses_list.getSelectedItem()
			old_nr = self.season_nr
			self.season_nr = item.getProperty('id')
			__settings__.setSetting('ses-' + self.serie_id, self.season_nr)
			__vdata__['season'] = int(self.season_nr)
			if __test__:
				seasons = re.compile('sid=81&ses=(.+?)".*?>(.+?)<').findall(__htm__.Page)
				__htm__.getPage( url=__cwd__ + '\\samples\\serie.htm', txdata=None )
			else:
				seasons = re.compile('sid=' + self.serie_id + '&ses=(.+?)".*?>(.+?)<').findall(__htm__.Page)
				__htm__.getPage( url='http://www.vplay.ro/serials/browse.do?sid=' + self.serie_id + '&ses=' + self.season_nr, txdata=None )

			self.ses_list.reset()
			for season_id, season_name in seasons:
				item = xbmcgui.ListItem(label=season_name)
				item.setProperty('id', season_id)
				if season_id==self.season_nr:
					item.setInfo('video', {'trailer':'s'})
				else:
					item.setInfo('video', {'trailer':'n'})
				self.ses_list.addItem(item)
			self.ses_list.selectItem(int(self.season_nr) - 1)
			
			self.loadEpisodes(__htm__.Page)

		elif controlId == 96:
			if __fav__.getFav( self.serie_id ):
				__fav__.delFav( self.serie_id )
				self.fav_button.setLabel('')
			else:
				__fav__.setFav( self.serie_id, self.getControl(95).getLabel() )
				self.fav_button.setLabel('FAV')

		elif controlId == 99:
			item = self.gen_list.getSelectedItem()
			print 'Item : [%s]' % item.getLabel()
			print 'ID   : [%s]' % item.getProperty('id')
			import resources.lib.Genre as Genre
			page_genre = Genre.GUI("vplay_search.xml", __cwd__, "default", id = item.getProperty('id'), name=item.getLabel())

	def loadEpisodes(self, page):
		self.ep_list.reset()
		episodes = re.compile('/watch/(.+?)/" class="serials-item".+?img src="(.+?)" width=(.+?)Episod.+? (.+?)<').findall(page)
		if (len(episodes)>0):
			i = 0
			for ep_id, img_url, watched, ep_nr in episodes:
				if __test__:
					img_url = 'D:\sample.jpg'
				item = xbmcgui.ListItem( label='Episodul '+ep_nr, iconImage=img_url, thumbnailImage=img_url )
				item.setProperty('id', ep_id)
				if ep_id in __pos__.List:
					item.setInfo('video', {'trailer':'p'}) # in progress
					self.selected_item = i
				elif (watched.find('Watched')>=0):
					item.setInfo('video', {'trailer':'w'}) # watched
					self.selected_item = i + 1
				self.ep_list.addItem(item)
				i = i + 1
			if self.selected_item==self.ep_list.size():
				self.selected_item = self.selected_item - 1
				print '--'
			print 'Selected item : [%s]' % str(self.selected_item)
			self.ep_list.selectItem(self.selected_item)
	
	def onAction(self, action):
		print 'Action code : [%s]' % str(action.getId())
		if action in self.action_cancel_dialog:
			self.close()
		elif action == 11:
			print 'Display info dialog'
			if len(self.description)>0:
				# dialog = xbmcgui.Dialog()
				# ok = dialog.ok('Rezumat', self.description, self.description, self.description)
				dialog = InfoDialog("vplay_info.xml", __cwd__, "default", text=self.description)

	def onFocus(self, controlId):
		pass

		
class InfoDialog(xbmcgui.WindowXMLDialog):
	def __init__(self, *args, **kwargs):
		xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
		self.text = kwargs['text']
		print self.text
		self.doModal()

	def onInit(self):
		self.action_cancel_dialog = (7, 9, 10, 11)
		if len(self.text)>0:
			self.getControl(95).setLabel(self.text)

	def onClick(self, controlId):
		# print 'Control ID : [%s]' % str(controlId)
		# if controlId == 96:
			# self.close()
		pass
	
	def onAction(self, action):
		print 'Action code : [%s]' % str(action.getId())
		if action in self.action_cancel_dialog:
			self.close()

	def onFocus(self, controlId):
		pass
